<template>
  <div class="content-wrapper">
    <div class="top-search-box">
      <!-- 高级查询 -->
      <a-form v-bind="layout" ref="formRef" :model="queryForm">
        <a-row :gutter="16">
          <a-col v-bind="colLayout.cols">
            <a-form-item label="名称">
              <a-input v-model:value="queryForm.portletName" placeholder="请输入名称" :allow-clear="true" @pressEnter="handleQuery" />
            </a-form-item>
          </a-col>
          <a-col v-bind="colLayout.cols">
            <a-form-item label="编码">
              <a-input v-model:value="queryForm.portletCode" placeholder="请输入编码" :allow-clear="true" @pressEnter="handleQuery" />
            </a-form-item>
          </a-col>
          <a-col v-bind="colLayout.cols">
            <a-form-item label="应用范围">
              <a-select
                v-model:value="queryForm.resourceType"
                :get-popup-container="(triggerNode) => triggerNode.parentNode"
                option-filter-prop="label"
                :show-search="true"
                :allow-clear="true"
                placeholder="请选择应用范围"
              >
                <a-select-option value="0" label="系统默认">系统默认</a-select-option>
                <a-select-option value="1" label="角色范围">角色范围</a-select-option>
                <a-select-option value="3" label="用户范围">用户范围</a-select-option>
                <a-select-option value="2" label="用户自定义">用户自定义</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col v-show="advanced" v-bind="colLayout.cols">
            <a-form-item label="是否默认">
              <a-select
                v-model:value="queryForm.isDefault"
                :get-popup-container="(triggerNode) => triggerNode.parentNode"
                option-filter-prop="children"
                :allow-clear="true"
                placeholder="请选择是否默认"
              >
                <a-select-option value="1">是</a-select-option>
                <a-select-option value="0">否</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col v-show="advanced" v-bind="colLayout.cols">
            <a-form-item label="描述">
              <a-input v-model:value="queryForm.memo" placeholder="请输入描述" :allow-clear="true" @pressEnter="handleQuery" />
            </a-form-item>
          </a-col>
          <a-col v-bind="colLayout.cols" style="margin-left: auto">
            <div class="table-page-search-submitButtons">
              <a-space>
                <a-button type="primary" @click="handleQuery">
                  <search-outlined />
                  查询
                </a-button>
                <a-button type="primary" ghost @click="resetQuery">
                  <redo-outlined />
                  清空
                </a-button>
                <a-button type="link" style="margin: 0" @click="toggleAdvanced">
                  {{ advanced ? '收起' : '展开' }}
                  <up-outlined v-if="advanced" />
                  <down-outlined v-else />
                </a-button>
              </a-space>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-wrapper">
      <AvicTable
        ref="portletConfig"
        table-key="portletConfig"
        :columns="columns"
        :row-key="(record) => record.id"
        :data-source="list"
        :loading="loading"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          columnWidth: 40,
          fixed: true
        }"
        :page-parameter="queryParam.pageParameter"
        :total="totalPage"
        @change="handleTableChange"
        @refresh="getList"
      >
        <template #toolBarLeft>
          <a-space>
            <a-button type="primary" title="添加" @click="handleAdd">
              <template #icon>
                <plus-outlined />
              </template>
              添加
            </a-button>
            <a-button
              v-hasPermi="['portlet:del']"
              danger
              :type="selectedRowKeys.length == 0 ? 'default' : 'primary'"
              title="删除"
              :loading="delLoading"
              @click="handleDelete(selectedRowKeys, '')"
            >
              <template #icon>
                <delete-outlined />
              </template>
              删除
            </a-button>
            <a-button type="primary" ghost title="复制" @click="handleCopy">
              <template #icon>
                <avic-icon svg="avic-file-copy-line" />
              </template>
              复制
            </a-button>
          </a-space>
        </template>
        <template #toolBarRight>
          <a-input-search
            class="opt-btn-commonsearch"
            style="width: 240px"
            placeholder="请输入名称或编码查询"
            title="请输入名称或编码查询"
            :allow-clear="true"
            @search="handleKeyWordQuery"
          />
        </template>
        <template #bodyCell="{ column, record, index, text }">
          <template v-if="column.dataIndex === 'id'">
            {{ index + 1 + queryParam.pageParameter.rows * (queryParam.pageParameter.page - 1) }}
          </template>
          <template v-else-if="column.dataIndex === 'resourceType'">
            <span v-if="text == '0'" title="系统默认">系统默认</span>
            <span v-if="text == '1'" title="角色范围">角色范围</span>
            <span v-if="text == '3'" title="用户范围">用户范围</span>
            <span v-if="text == '2'" title="系统默认">用户自定义</span>
          </template>
          <template v-else-if="column.dataIndex === 'isDefault'">
            <span v-if="text == '0'" title="否">否</span>
            <span v-if="text == '1'" title="是">是</span>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-button v-hasPermi="['portlet:edit']" type="link" class="inner-btn" @click.stop="handleEdit(record.id)">编辑</a-button>
            <a-button type="link" class="inner-btn" @click.stop="handleSettingOrView(record, 'setting')">设计</a-button>
            <a-button type="link" class="inner-btn" @click.stop="handleSettingOrView(record, 'view')">预览</a-button>
          </template>
        </template>
      </AvicTable>
    </div>
    <!-- 添加页面弹窗 -->
    <SysThemesSkinsPortletAdd
      v-if="showAddModal"
      ref="addModal"
      @openDesignModal="openDesignModal"
      @reloadData="getList"
      @close="showAddModal = false"
    />
    <!-- 编辑页面弹窗 -->
    <SysThemesSkinsPortletEdit
      v-if="showEditModal"
      ref="editModal"
      :form-id="formId"
      @reloadData="getList"
      @close="showEditModal = false"
    />
    <!-- 设计页面弹窗 -->
    <PortalDesignerModal
      v-if="showDesignerModal"
      ref="portalDesignerModal"
      :portal-info="portalInfo"
      @updatePortalList="getList"
      @reloadData="getList"
      @closeModal="showDesignerModal = false"
    />
    <!-- 预览页面弹窗 -->
    <AvicModal
      title="预览"
      :visible="previewVisible"
      :full-screen="true"
      :adjust-size="false"
      :body-style="{ background: '#F1F3F9' }"
      :footer="null"
      @cancel="previewVisible = false"
    >
      <GeneratePortal v-if="previewVisible" :data="designContent" :preview="true" />
    </AvicModal>
  </div>
</template>
<script lang="ts" setup>
// 引入模块DTO
import type { PortletConfigDto } from '@/api/avic/system/PortalApi';
// 引入模块API
import { listPortalConfigByPage, getPortletContentById, delPortletConfig, copyPortletConfig } from '@/api/avic/system/PortalApi';
// 引入添加页面组件
import SysThemesSkinsPortletAdd from './SysThemesSkinsPortletAdd.vue';
// 引入编辑页面组件
import SysThemesSkinsPortletEdit from './SysThemesSkinsPortletEdit.vue';
// 引入设计页面组件
import PortalDesignerModal from '@/components/portal-designer/PortalDesignModal.vue';
// 引入预览页面组件
import GeneratePortal from '@/components/portal-designer/components/GeneratePortal.vue';
const { proxy } = getCurrentInstance();
const layout = {
  labelCol: { flex: '0 0 120px' },
  wrapperCol: { flex: '1 1 0' }
};
const colLayout = proxy.$colLayout4; // 页面表单响应式布局对象
const columns = [
  {
    title: '名称',
    dataIndex: 'portletName',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '编码',
    dataIndex: 'portletCode',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '应用范围',
    dataIndex: 'resourceType',
    width: 120,
    align: 'center'
  },
  {
    title: '是否默认',
    dataIndex: 'isDefault',
    width: 100,
    align: 'center'
  },
  {
    title: '排序',
    dataIndex: 'orderBy',
    ellipsis: true,
    width: 100,
    align: 'canter'
  },
  {
    title: '描述',
    dataIndex: 'memo',
    ellipsis: true,
    minWidth: 120,
    resizable: true
  },
  {
    title: '操作',
    dataIndex: 'action',
    ellipsis: true,
    width: 180,
    align: 'center',
    fixed: 'right'
  }
];
const queryForm = ref<PortletConfigDto>({});
const queryParam = reactive({
  // 请求表格数据参数
  pageParameter: {
    page: 1, // 页数
    rows: 20 // 每页条数
  },
  searchParams: {
    ...queryForm.value
  },
  keyWord: ref(''), // 快速查询数据
  sidx: null, // 排序字段
  sord: null // 排序方式: desc降序 asc升序
});
const showAddModal = ref(false); // 是否展示添加弹窗
const showEditModal = ref(false); // 是否展示编辑弹窗
const advanced = ref(false); // 高级搜索 展开/关闭
const showDesignerModal = ref(false); // 是否展示设计弹窗
const previewVisible = ref(false); // 是否展示预览弹窗
const designContent = ref();
const portalInfo = ref();
const list = ref([]); // 表格数据集合
const formId = ref(''); // 当前行数据id
const selectedRowKeys = ref([]); // 选中数据主键集合
const loading = ref(false);
const delLoading = ref(false);
const totalPage = ref(0);
onMounted(async () => {
  // 加载表格数据
  getList();
});

/** 查询数据 */
function getList() {
  selectedRowKeys.value = []; // 清空选中
  loading.value = true;
  listPortalConfigByPage(queryParam)
    .then((response) => {
      list.value = response.data.result;
      totalPage.value = response.data.pageParameter.totalCount;
      loading.value = false;
    })
    .catch(() => {
      list.value = [];
      totalPage.value = 0;
      loading.value = false;
    });
}
/** 高级查询 查询按钮操作 */
function handleQuery() {
  queryParam.searchParams = queryForm.value;
  queryParam.keyWord = '';
  queryParam.pageParameter.page = 1;
  getList();
}
/** 高级查询 重置按钮操作 */
function resetQuery() {
  queryForm.value = {};
  handleQuery();
}
/** 高级查询 展开/收起 */
function toggleAdvanced() {
  advanced.value = !advanced.value;
}
/**
 * 快速查询逻辑
 * @param value 查询内容
 */
function handleKeyWordQuery(value: string) {
  const keyWord = {
    portletName: value,
    portletCode: value
  };
  queryParam.keyWord = value ? JSON.stringify(keyWord) : '';
  queryParam.pageParameter.page = 1;
  getList();
}
/** 添加 */
function handleAdd() {
  showAddModal.value = true;
}
/** 复制 */
function handleCopy() {
  if (selectedRowKeys.value.length === 0) {
    proxy.$message.warning('请选择要复制的数据！');
    return;
  }
  if (selectedRowKeys.value.length > 1) {
    proxy.$message.warning('只允许选择一条数据，进行复制！');
    return;
  }
  proxy.$confirm({
    title: `确认要复制选择的数据吗？`,
    okText: '确定',
    cancelText: '取消',
    centered: true,
    onOk: () => {
      copyPortletConfig(selectedRowKeys.value[0]).then((res) => {
        if (res.success) {
          proxy.$message.success('复制成功！');
          getList();
        }
      });
    }
  });
}
/**
 * 编辑
 * @param id 行数据id
 */
function handleEdit(id: string) {
  formId.value = id;
  showEditModal.value = true;
}
/**
 * 删除
 * @param ids 选中数据id集合
 * @param type 删除类型：表头、行内
 */
function handleDelete(ids: string[], type: string) {
  if (ids.length === 0) {
    proxy.$message.warning('请选择要删除的数据！');
    return;
  }
  proxy.$confirm({
    title: `确认要删除${type === 'row' ? '当前行的' : '已选'}数据吗？`,
    okText: '确定',
    cancelText: '取消',
    centered: true,
    onOk: () => {
      delLoading.value = true;
      delPortletConfig(ids.join(','))
        .then((res) => {
          if (res.success) {
            proxy.$message.success('删除成功！');
            getList();
          }
          delLoading.value = false;
        })
        .catch(() => {
          delLoading.value = false;
        });
    }
  });
}
/**
 * 选中项发生变化时的回调
 * @param rowKeys 选中项id集合
 */
function onSelectChange(_selectedRowKeys: string[]) {
  selectedRowKeys.value = _selectedRowKeys;
}
/**
 * 分页、排序、筛选变化时触发
 * @param pagination 分页信息
 * @param _filters 筛选信息
 * @param sorter 排序信息
 */
function handleTableChange(pagination, _filters, sorter) {
  queryParam.pageParameter.page = pagination.current;
  queryParam.pageParameter.rows = pagination.pageSize;
  if (proxy.$objIsNotBlank(sorter.field)) {
    queryParam.sidx = sorter.field;
    queryParam.sord = sorter.order === 'ascend' ? 'asc' : 'desc'; // 排序方式: desc降序 asc升序
  }
  getList();
}
/**
 * 打开设计弹窗
 * @param data 设计数据
 */
function openDesignModal(data) {
  showDesignerModal.value = true;
  portalInfo.value = data;
  portalInfo.value.setting = true;
}
/**
 * 设计/预览
 * @param record 行数据
 * @param flag 类型：设计、预览
 */
function handleSettingOrView(record, flag: string) {
  if (!record.id) return;
  getPortletContentById(record.id).then((res) => {
    if (res.data) {
      res.data.content = res.data.content || null;
      const result = {
        ...res,
        content: JSON.parse(res.data.content),
        ...record
      };
      portalInfo.value = result;
      portalInfo.value.setting = true;
      designContent.value = JSON.parse(res.data.content);
      if (designContent.value == null) {
        designContent.value = {
          config: {
            gutter: '15px',
            labelPosition: 'right',
            labelWidth: 100,
            size: 'small'
          },
          list: []
        };
      }
      if (flag === 'setting') {
        showDesignerModal.value = true;
      } else {
        previewVisible.value = true;
      }
    }
  });
}
</script>
